//
//  DLBaseTextField.m
//  Base
//
//  Created by apple on 16/11/7.
//  Copyright © 2016年 dgg. All rights reserved.
//

#import "DLBaseTextField.h"

#define kdefutNum 50
@implementation DLBaseTextField
- (void)awakeFromNib
{
    [super awakeFromNib];
    self.subText = @"";
    self.delegate = self;
    [self addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    self.autocorrectionType=UITextAutocorrectionTypeNo;
}

-(instancetype)init
{
    if (self = [super init]) {
        self.subText = @"";
        self.delegate = self;
        [self addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
        self.autocorrectionType=UITextAutocorrectionTypeNo;
    }
    return self;
}
-(instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        self.subText = @"";
        self.delegate = self;
        [self addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
        self.autocorrectionType=UITextAutocorrectionTypeNo;
    }
    return self;
    
}

-(void)setTextState:(NSInteger)textState
{
    _textState = textState;
    
    switch (textState) {
        case TextState_default:
        {
            self.keyboardType = UIKeyboardTypeDefault;
        }
            break;
        case TextState_phone:
        {
            self.keyboardType = UIKeyboardTypeNumberPad;
        }
            break;
        case TextState_int:
        {
            self.keyboardType = UIKeyboardTypeNumberPad;
        }
            break;
        case TextState_money:
        {
            self.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
        }
            break;
        case TextState_cardId:
        {
            self.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
        }
            break;
        case TextState_BFB:
        {
            self.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
        }
            break;
        case TextState_email:
        {
            self.keyboardType = UIKeyboardTypeEmailAddress;
        }
            break;
        case TextState_landline:
        {
            self.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
        }
            break;
        case TextState_bankCard:
        {
            self.keyboardType = UIKeyboardTypeNumberPad;
        }
            break;
        case TextState_name:
        {
            self.keyboardType = UIKeyboardTypeDefault;
        }
            break;
            
        default:
            break;
    }
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    if ([NSString isEmpty:textField.text.trimString]) {
        self.text = @"";
        if ([self.myDelegate respondsToSelector:@selector(textFieldDidEndEditing:)]) {
            [self.myDelegate textFieldDidEndEditing:self];
        }
        return;
    }
    
    switch (self.textState) {
        case TextState_default://默认类型，
        {
            
            
            if ([self.myDelegate respondsToSelector:@selector(textFieldDidEndEditing:)]) {
                [self.myDelegate textFieldDidEndEditing:self];
            }
            
        }
            break;
        case TextState_phone://手机号码textField.text.trimString
        {
            if ([DLValidation validateMobile:textField.text.trimString]) {
                if ([self.myDelegate respondsToSelector:@selector(textFieldDidEndEditing:)]) {
                    [self.myDelegate textFieldDidEndEditing:self];
                }
            }else
            {
                [self TextFieldValiteErrorMsg:@"手机号码由11位数字组成"];
            }
        }
            break;
            
        case TextState_int://整形
        {
            if (![DLValidation isPureInt:textField.text.trimString]) {
                
                [self TextFieldValiteErrorMsg:@"请输入正确的数字"];

            }else
            {
                
                if ([self.myDelegate respondsToSelector:@selector(textFieldDidEndEditing:)]) {
                    [self.myDelegate textFieldDidEndEditing:self];
                }
                
            }
        }
            break;
        case TextState_money://金额类型
        {
            
            if ([DLValidation isMoney:textField.text.trimString]) {
                if ([self.myDelegate respondsToSelector:@selector(textFieldDidEndEditing:)]) {
                    [self.myDelegate textFieldDidEndEditing:self];
                }
            }else
            {
                [self TextFieldValiteErrorMsg:@"金额最多保留小数点后两位，只能输入数字和小数点"];
            }
        }
            break;
        case TextState_cardId://身份证
        {
            
            
            
            if ([DLValidation isCardIDWithStr:textField.text.trimString]) {
                if ([self.myDelegate respondsToSelector:@selector(textFieldDidEndEditing:)]) {
                    [self.myDelegate textFieldDidEndEditing:self];
                }
            }else
            {
                [self TextFieldValiteErrorMsg:@"身份证号码长度为15位或者18位"];
            }
            
        }
            break;
        case TextState_BFB://百分比整形 0-100
        {
            if ([DLValidation isMoney:textField.text.trimString]) {
                if ([self.myDelegate respondsToSelector:@selector(textFieldDidEndEditing:)]) {
                    [self.myDelegate textFieldDidEndEditing:self];
                }
            }else
            {
                [self TextFieldValiteErrorMsg:@"百分比为0~100之间的数字，小数点后保留两位"];
            }
        }
            break;
        case TextState_email://邮箱类型
        {
            if ([DLValidation isValidateEmail:textField.text.trimString]) {
                if ([self.myDelegate respondsToSelector:@selector(textFieldDidEndEditing:)]) {
                    [self.myDelegate textFieldDidEndEditing:self];
                }
            }else
            {
                [self TextFieldValiteErrorMsg:@"邮箱格式错误"];
            }
        }
            break;
        case TextState_landline://座机类型
        {
            
            if ([DLValidation isLandlineWithNum:textField.text.trimString]) {
                if ([self.myDelegate respondsToSelector:@selector(textFieldDidEndEditing:)]) {
                    [self.myDelegate textFieldDidEndEditing:self];
                }
            }else
            {
                [self TextFieldValiteErrorMsg:@"座机号码输入格式错误\n如有区号请加上区号(如:028-)"];
            }
        }
            break;
        case TextState_bankCard:
        {
            if ([self.myDelegate respondsToSelector:@selector(textFieldDidEndEditing:)]) {
                [self.myDelegate textFieldDidEndEditing:self];
            }
        }
            break;
        case TextState_name:
        {
            if ([DLValidation isfullNameWithStr:textField.text.trimString]) {
                if ([self.myDelegate respondsToSelector:@selector(textFieldDidEndEditing:)]) {
                    [self.myDelegate textFieldDidEndEditing:self];
                }
            }else{
                [self TextFieldValiteErrorMsg:@"姓名输入格式错误"];
            }
        }
            break;
        default:
            break;
    }
}

- (void)textFieldDidChange:(UITextField *)textField
{
    if ([NSString isEmpty:textField.text.trimString]) {
        self.subText  = @"";
        return;
    }else if ([[[textField textInputMode] primaryLanguage] isEqualToString:@"emoji"]) {
        textField.text = self.subText;
        return;
    }else if ([self isContainsTwoEmoji:textField.text])
    {
        textField.text = self.subText;
        return;
    }else
    {
        self.subText = textField.text ;
    }
    
    
    switch (self.textState) {
        case TextState_default://默认类型，
        {
            
            if (textField.text.trimString.length > ((self.textNumber>0)?self.textNumber:kdefutNum)) {
                
                
                NSString *lang = [[textField textInputMode]primaryLanguage];//键盘输入模式
                if ([lang isEqualToString:@"zh-Hans"]) {// 简体中文输入，包括简体拼音，健体五笔，简体手写
                    UITextRange *selectedRange = [textField markedTextRange];
                    //获取高亮部分
                    UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
                    //没有高亮选择的字，则对已输入的文字进行字数统计和限制
                    if (!position) {
                        
                        textField.text = [textField.text.trimString substringToIndex:((self.textNumber>0)?self.textNumber:kdefutNum)];
                    }
                    //有高亮选择的字符串，则暂不对文字进行统计和限制
                    else{
                        
                    }
                }
                // 中文输入法以外的直接对其统计限制即可，不考虑其他语种情况
                else{
                    
                    textField.text = [textField.text.trimString substringToIndex:((self.textNumber>0)?self.textNumber:kdefutNum)];
                }
                
                
                
                
                
            }
            
        }
            break;
        case TextState_phone://手机号码
        {
            
            
            if (textField.text.trimString.length > 11) {
                textField.text = [textField.text.trimString substringToIndex:11];
            }else
            {
                
                if (![NSString isEmpty:textField.text.trimString]) {
                    NSMutableString * mobile = textField.text.trimString.mutableCopy;
                    while (mobile.length < 11) {
                        [mobile appendString:@"3"];
                    }
                    if ([DLValidation validateMobile:mobile]) {
                        
                    }else
                    {
                        textField.text = [textField.text.trimString substringToIndex:textField.text.trimString.length -1];
                        [self textFieldDidChange:textField];
                    }
                    
                }
                
            }
        }
            break;
        case TextState_int:
        {
            if (![DLValidation isPureInt:textField.text.trimString]) {
                
                textField.text = [textField.text.trimString substringToIndex:textField.text.trimString.length -1];
                [self textFieldDidChange:textField];
            }else
            {
                if (textField.text.trimString.length >((self.textNumber>0)?self.textNumber: 50)) {
                    textField.text = [textField.text.trimString substringToIndex:((self.textNumber>0)?self.textNumber:50)];
                }
            }
            
        }
            break;
        case TextState_money://金额类型
        {
            if (![DLValidation isMoney:textField.text.trimString]) {
                textField.text = [textField.text.trimString substringToIndex:textField.text.trimString.length -1];
                [self textFieldDidChange:textField];
            }else
            {
                
                NSArray *strArray = [textField.text.trimString componentsSeparatedByString:@"."];
                if (strArray.count >0) {
                    NSMutableString *str = [NSMutableString stringWithString:strArray[0]];
                    NSInteger textNum = self.textNumber>0?self.textNumber:11;
                    if([str hasPrefix:@"-"]){
                        textNum += 1;
                    }
                    if (str.length >textNum) {
                        str = [textField.text.trimString substringToIndex:textNum].mutableCopy;
                    }
                    if (strArray.count>1) {
                        [str appendFormat:@".%@",strArray[1]];
                    }
                    
                    textField.text = str;
                }
            }
            
        }
            break;
        case TextState_cardId://身份证
        {
            
            if (textField.text.trimString.length > 18) {
                textField.text = [textField.text.trimString substringToIndex:18];
            }
            
        }
            break;
        case TextState_BFB://百分比整形 0-100
        {
            if (![DLValidation isMoney:textField.text.trimString]) {
                textField.text = [textField.text.trimString substringToIndex:textField.text.trimString.length -1];
                [self textFieldDidChange:textField];
            }else
            {
                
                NSArray *strArray = [textField.text.trimString componentsSeparatedByString:@"."];
                if (strArray.count >0) {
                    NSMutableString *str = [NSMutableString stringWithString:strArray[0]];
                    if (str.length > ((self.textNumber >0 )? self.textNumber:11)) {
                        str = [textField.text.trimString substringToIndex:((self.textNumber >0 )? self.textNumber:11)].mutableCopy;
                    }
                    if (strArray.count>1) {
                        [str appendFormat:@".%@",strArray[1]];
                    }
                    
                    if ([str doubleValue]> ((self.textNumber >0 )? self.textNumber:100)) {
                        str = [NSString stringWithFormat:@"%ld",(long)((self.textNumber >0) ? self.textNumber:100)].mutableCopy;
                    }
                    textField.text = str;
                }
            }
        }
            break;
        case TextState_email://邮箱类型
        {
            if (textField.text.trimString.length > ((self.textNumber>0)?self.textNumber:kdefutNum)) {
                textField.text = [textField.text.trimString substringToIndex:((self.textNumber>0)?self.textNumber:kdefutNum)];
            }
        }
            break;
            
        case TextState_landline://座机类型
        {
            if (![NSString isEmpty:textField.text.trimString]) {
                NSMutableString * landlineNum1 = textField.text.trimString.mutableCopy;
                NSMutableString * landlineNum2 = textField.text.trimString.mutableCopy;
                
                
                if ([landlineNum1 containsString:@"-"]) {
                    while (landlineNum1.length < 12) {
                        [landlineNum1 appendString:@"3"];
                    }
                }else
                {
                    while (landlineNum1.length < 8) {
                        [landlineNum1 appendString:@"3"];
                    }
                }
                
                while (landlineNum2.length < 11) {
                    [landlineNum2 appendString:@"3"];
                }
                if ([DLValidation isLandlineWithNum:landlineNum2]||[DLValidation isLandlineWithNum:landlineNum1])
                {
                    
                    
                }else
                {
                    textField.text = [textField.text.trimString substringToIndex:textField.text.trimString.length -1];
                    [self textFieldDidChange:textField];
                }
                
            }
        }
            break;
        case TextState_bankCard:
        {
            if (![NSString isEmpty:textField.text.trimString]) {
                NSString *text = [textField.text.trimString stringByReplacingOccurrencesOfString:@" " withString:@""];
                NSMutableString *newText = [NSMutableString string];
                for (int i = 0; i < MIN(text.length, self.textNumber > 0 ? self.textNumber : 19); i++) {
                    NSString *sub = [text substringWithRange:NSMakeRange(i, 1)];
                    [newText appendString:sub];
                    if (i < text.length - 1 && (i + 1) % 4 == 0) {
                        [newText appendString:@" "];
                    }
                }
                textField.text = [newText copy];
            }
        }
            break;
        case TextState_name:
        {
            if (textField.text.trimString.length > 20) {
                textField.text = [textField.text.trimString substringToIndex:20];
            }
        }
            break;
        default:
            break;
    }
    
}

- (void)textFieldDidBeginEditing:(DLBaseTextField *)textField
{
    if ([self.myDelegate respondsToSelector:@selector(textFieldDidBeginEditing:)]) {
        [self.myDelegate textFieldDidBeginEditing:self];
    }
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    
    if ([self.myDelegate respondsToSelector:@selector(textFieldShouldBeginEditing:)]) {
        return  [self.myDelegate textFieldShouldBeginEditing:self];
    }
    
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    if([self.myDelegate respondsToSelector:@selector(textFieldShouldReturn:)]){
        [self.myDelegate textFieldShouldReturn:self];
    }
    if(self.delegate != self){
        if([self.delegate respondsToSelector:@selector(textFieldShouldReturn:)]){
            [self.delegate textFieldShouldReturn:self];
        }
    }
    return YES;
}


-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if([self.myDelegate respondsToSelector:@selector(textField:shouldChangeCharactersInRange:replacementString:)]){
        return [self.myDelegate textField:self shouldChangeCharactersInRange:range replacementString:string];
    }
    if(self.delegate != self){
        if([self.delegate respondsToSelector:@selector(textField:shouldChangeCharactersInRange:replacementString:)]){
            return  [self.delegate textField:self shouldChangeCharactersInRange:range replacementString:string];
        }
    }
    return YES;
}

#pragma mark -

- (void)TextFieldValiteErrorMsg:(NSString *)errorMsg{
    if ([self.myDelegate respondsToSelector:@selector(textFieldValiteError:errorMsg:)]) {
        [self.myDelegate textFieldValiteError:self errorMsg:errorMsg];
    }
    if (self.textFieldValiteErrorBlock) {
        self.textFieldValiteErrorBlock(self, errorMsg);
    }
}

//限制输入表情
- (BOOL)isContainsTwoEmoji:(NSString *)string {
    __block BOOL returnValue = NO;
    [string enumerateSubstringsInRange:NSMakeRange(0, [string length])
                               options:NSStringEnumerationByComposedCharacterSequences
                            usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
                                const unichar hs = [substring characterAtIndex:0];
                                if (0xd800 <= hs && hs <= 0xdbff) {
                                    if (substring.length > 1) {
                                        const unichar ls = [substring characterAtIndex:1];
                                        const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                                        if (0x1d000 <= uc && uc <= 0x1f77f) {
                                            returnValue = YES;
                                        }
                                    }
                                } else if (substring.length > 1) {
                                    const unichar ls = [substring characterAtIndex:1];
                                    if (ls == 0x20e3) {
                                        returnValue = YES;
                                    }
                                    
                                } else {
                                    if (0x2100 <= hs && hs <= 0x27ff) {
                                        returnValue = YES;
                                    } else if (0x2B05 <= hs && hs <= 0x2b07) {
                                        returnValue = YES;
                                    } else if (0x2934 <= hs && hs <= 0x2935) {
                                        returnValue = YES;
                                    } else if (0x3297 <= hs && hs <= 0x3299) {
                                        returnValue = YES;
                                    } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {
                                        returnValue = YES;
                                    }else if (hs == 0x200d){
                                        returnValue = YES;
                                    }
                                }
                            }];
    
    return returnValue;
}

@end
